package com.aglow.bluetoothspeaker.main.ui.fragment;

import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.aglow.bluetoothspeaker.R;
import com.aglow.bluetoothspeaker.main.base.BaseFragment;
import com.aglow.bluetoothspeaker.main.ui.adapter.MusicListAdapter;
import com.aglow.bluetoothspeaker.model.bean.Music;
import com.aglow.bluetoothspeaker.model.cache.MusicCache;
import com.aglow.bluetoothspeaker.model.event.ItemItentEvent;
import com.aglow.bluetoothspeaker.model.event.LocalMusicScanSuccessEvent;
import com.aglow.bluetoothspeaker.presenter.lisnter.OnItemClickListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class MusicListFragment extends BaseFragment {
    @BindView(R.id.rv_music_list)
    RecyclerView rvMusicList;
    Unbinder unbinder;
    private MusicListAdapter Adapter;
    private List<Music> mMusicList = new ArrayList<>();

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_music_list, container, false);
    }

    @Override
    public void initData() {
        Adapter = new MusicListAdapter(mContext, mMusicList);
        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {
        rvMusicList.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL));
        rvMusicList.setLayoutManager(new LinearLayoutManager(mContext));
        rvMusicList.setAdapter(Adapter);
    }

    @Override
    public void addViewListener() {
        Adapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view) {
                int position = rvMusicList.getChildAdapterPosition(view);
                MusicCache.getPlayService().play(position);
                //跳转viewpager
                EventBus.getDefault().post(new ItemItentEvent());
            }
        });
    }
    @SuppressWarnings("unused")
    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void updateMusicList(LocalMusicScanSuccessEvent event) {
        mMusicList.clear();

        mMusicList.addAll(event.getMusicList());
        Adapter.notifyDataSetChanged();
    }




    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);

    }
}
